/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.telsoft.hms.lib.security.session;

import java.util.concurrent.ConcurrentHashMap;

import com.telsoft.hms.lib.security.exception.SessionNotExistsException;
import com.telsoft.hms.lib.security.exception.SessionRejectedException;
import com.telsoft.hms.lib.security.core.AbstractSession;
import com.telsoft.hms.lib.security.core.AbstractSessionManager;

/**
 * @author VIETPH
 * NgÃ y táº¡o: 12/09/2014
 */

public class SessionManager extends AbstractSessionManager {

    private ConcurrentHashMap<Long, SessionCount> mSessionsCount;
    
    public SessionManager(int intervalCheckSessionTimeout) {
        super(intervalCheckSessionTimeout);
        this.mSessionsCount = new ConcurrentHashMap<>();
    }

    // override láº¡i phÆ°Æ¡ng thá»©c validate session trÆ°á»›c khi add vÃ o list
    // thÃªm bÆ°á»›c táº¡o bá»™ Ä‘áº¿m sá»‘ session cá»§a má»™t user Ä‘Äƒng nháº­p cÃ¹ng má»™t thá»�i Ä‘iá»ƒm vÃ  tÄƒng lÃªn má»—i khi má»™t user Ä‘Äƒng nháº­p trÃªn nhiá»�u thiáº¿t bá»‹
    @Override
    protected synchronized void validateNewSession(AbstractSession abtractSession) throws SessionRejectedException {
        Session session = (Session) abtractSession;
        SessionCount ssCount = mSessionsCount.get(session.getUserId());
        if (ssCount == null) {
            mSessionsCount.put(session.getUserId(), new SessionCount());
        } else { //!= null
            //Há»¦Y if (ssCount.howMany() >= mbyteMaxSessionCountPerEachUserId) {
            if (ssCount.howMany() >= session.getMaxSessionAllowed()) {
                throw new SessionRejectedException("Maximum logon per each user ("+session.getMaxSessionAllowed()+") has been reached");
            } else {
                ssCount.increase();
            }
        }
    }

    // override láº¡i phÆ°Æ¡ng thá»©c xÃ³a session ra khá»�i list
    // thÃªm bÆ°á»›c Ä‘áº¿m láº¡i session cá»§a má»™t user Ä‘Äƒng nháº­p cÃ¹ng má»™t thá»�i Ä‘iá»ƒm
    @Override
    public synchronized void removeSession(String securityKey) {
        try {
            long userId = ((Session) getSession(securityKey)).getUserId();
            SessionCount ssCount = mSessionsCount.get(userId);
            if (ssCount != null) {
                ssCount.decrease();
                if (ssCount.howMany() == 0){
                    mSessionsCount.remove(userId);
                }
            }
        } catch (SessionNotExistsException ex) {
            // thÃ´ng tin session count cá»§a user nÃ y khÃ´ng tá»“n táº¡i
        } finally {
            super.removeSession(securityKey); //To change body of generated methods, choose Tools | Templates.
        }
    }
}
